package com.sk.sourcecircle.activity.find;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.find.fragment.RoundAlbumFragment;
import com.sk.sourcecircle.activity.find.fragment.RoundSourceFragment;
import com.sk.sourcecircle.activity.find.fragment.RoungGroupFragment;
import com.sk.sourcecircle.activity.home.activity.AddFriendActivity;
import com.sk.sourcecircle.activity.home.activity.ChooseCityActivity;
import com.sk.sourcecircle.activity.home.activity.RoundGroupActivity;
import com.sk.sourcecircle.activity.home.activity.SearchActivity;
import com.sk.sourcecircle.activity.main.MainActivity;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.entity.MyCity;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.zxing.activity.CaptureActivity;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/19.
 */

@RuntimePermissions
public class FindFragment extends BaseFragment implements View.OnClickListener, IUiListener {
    @BindView(R.id.switch_city)
    TextView switchCity;
    @BindView(R.id.search_view)
    TextView searchView;
    @BindView(R.id.title_menu)
    ImageView titleMenu;
    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.my_pager)
    ViewPager myPager;

    RoundSourceFragment roundSourceFragment;
    RoungGroupFragment roungGroupFragment;
    RoundAlbumFragment roundAlbumFragment;
    private List<Fragment> fragmentList = new ArrayList<>();

    private boolean isopen = false;
    PopupWindow popupWindow;

    private String jsonArea;
    private String city;


    @Override
    protected int getContentView() {
        return R.layout.fragment_find;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initFragments();
        switchCity.setText(MyApplication.getInstance().getCityName());
    }

    public void setSwitchCity(String city) {
        this.city = city;
        switchCity.setText(city);
    }

    private void initFragments() {

        roundSourceFragment = new RoundSourceFragment();
        roungGroupFragment = new RoungGroupFragment();
        roundAlbumFragment = new RoundAlbumFragment();

        fragmentList.add(roundSourceFragment);
        fragmentList.add(roungGroupFragment);
        fragmentList.add(roundAlbumFragment);

        myPager.setOffscreenPageLimit(3);

        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager(), getResources().getStringArray(R.array.find_array), fragmentList);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);
    }


    private void showPopWindow() {
        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.home_pop, relativeLayout, false);
        TextView addFriend = view.findViewById(R.id.add_friend);
        TextView roundGroup = view.findViewById(R.id.round_group);
        TextView share = view.findViewById(R.id.share);
        TextView scan = view.findViewById(R.id.scan);
        addFriend.setOnClickListener(this);
        roundGroup.setOnClickListener(this);
        share.setOnClickListener(this);
        scan.setOnClickListener(this);
        relativeLayout.addView(view);
        popupWindow = new PopupWindow(relativeLayout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setClippingEnabled(false);

        ColorDrawable dw = new ColorDrawable(0);
        popupWindow.setBackgroundDrawable(dw);

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        relativeLayout.measure(w, h);
        int width = relativeLayout.getMeasuredWidth();
        popupWindow.showAsDropDown(titleMenu, -width + titleMenu.getMeasuredWidth(), 0);
        isopen = true;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_friend:
                Intent addIntent = new Intent(mContext, AddFriendActivity.class);
                startActivity(addIntent);
                popupWindow.dismiss();
                isopen = false;
                break;
            case R.id.round_group:
                Intent groupIntent = new Intent(mContext, RoundGroupActivity.class);
                startActivity(groupIntent);
                popupWindow.dismiss();
                isopen = false;

                break;
            case R.id.share:
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setTargetUrl(Constants.App_url);
                shareDialogFragment.setImageUrl("");
                shareDialogFragment.setQqListener(this);
                shareDialogFragment.setTitle("源圈");
                shareDialogFragment.setSummary("源圈社区”是北京源圈传媒科技有限公司自主开发运营的一款APP应用，是消费升级领域首家本地化精准数据匹配平台。以本地化社群APP为载体，用户运营为中心，串连社区、中小微企业、校园三大场景，运用“去中心化”的平台方式，让各实体社群实现精准用户运营、精准需求匹配、精准营销推广。立志成为一个让人人都能实现价值的平台、一个基于实体场景的精准大数据平台。");
                shareDialogFragment.show(getActivity().getFragmentManager(), "share");
                popupWindow.dismiss();
                isopen = false;

                break;
            case R.id.scan:
                popupWindow.dismiss();
                isopen = false;
                FindFragmentPermissionsDispatcher.startScanWithPermissionCheck(this);
                break;
        }
    }


    @OnClick({R.id.search_view, R.id.title_menu,R.id.switch_city})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.switch_city:
                Intent switchIntent = new Intent(mContext, ChooseCityActivity.class);
                if (getActivity() instanceof MainActivity) {
                    jsonArea = ((MainActivity) getActivity()).getAresJson();
                }
                switchIntent.putExtra("data", jsonArea);
                switchIntent.putExtra("city", city);
                startActivityForResult(switchIntent, 1);
                break;
            case R.id.search_view:
                Intent seatchIntent = new Intent(mContext, SearchActivity.class);
                startActivity(seatchIntent);
                break;
            case R.id.title_menu:
                if (!isopen) {
                    showPopWindow();
                } else {
                    isopen = false;
                    popupWindow.dismiss();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 1) {
                MyCity city = data.getParcelableExtra("data");
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).setCity(city.getCity_name(),city.getCity_id());
                    MyApplication.getInstance().setCityId(city.getCity_id());
                    MyApplication.getInstance().setCityName(city.getCity_name());
                }
            }
        }
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startScan() {
        Intent scanIntent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(scanIntent, 1);

    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("扫一扫需要使用您的相机！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        SnackUtils.showError(mRootView,"您拒绝了相机权限！");
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止定位权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FindFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
